function [globalBest, globalBestFitness, FitnessHistory] = DE(popsize, maxIteration,dim, LB, UB, F, CR, Fun)
% 种群的初始化和计算适应度值
Sol(popsize, dim) = 0; % Declare memory.
Fitness(popsize) = 0;
for i = 1:popsize
    Sol(i,:) = LB+(UB-LB).* rand(1, dim);
    Fitness(i) = Fun(Sol(i,:));
end

% 获得全局最优值以及对应的种群向量
[fbest, bestIndex] = min(Fitness);
globalBest = Sol(bestIndex,:); 
globalBestFitness = fbest; 

% 开始迭代
for time = 1:maxIteration
    for i = 1:popsize
        % 突变
        r = randperm(popsize, 3);  
        mutantPos = Sol(r(1),:) + F * (Sol(r(2),:) - Sol(r(3),:));%在1~pop中随机选择5个数组成一个数组
        
        % 交叉
        jj = randi(dim);  % 选择至少一维发生交叉
        for d = 1:dim
            if rand() < CR || d == jj
                crossoverPos(d) = mutantPos(d);
            else
                crossoverPos(d) = Sol(i,d);
            end
        end
        
        % 检查是否越界.
        crossoverPos(crossoverPos>UB) = UB(crossoverPos>UB); 
        crossoverPos(crossoverPos<LB) = LB(crossoverPos<LB);
        
        evalNewPos = Fun(crossoverPos);% 将突变和交叉后的变量重新评估
        % 小于原有值就更新
        if evalNewPos < Fitness(i)
            Sol(i,:) = crossoverPos;
            Fitness(i) = evalNewPos;
        end
    end
    [fbest, bestIndex] = min(Fitness);
    globalBest = Sol(bestIndex,:);
    globalBestFitness = fbest;
    
    % 存储每次迭代的最优值.
    FitnessHistory(time) = fbest;
end
end